package com.iwomy.secureplat.platform.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iwomy.secureplat.admin.api.entity.SysDept;
import com.iwomy.secureplat.admin.api.vo.SysDeptVO;
import com.iwomy.secureplat.common.core.util.R;
import com.iwomy.secureplat.common.security.util.SecurityUtils;
import com.iwomy.secureplat.platform.dto.BasicExpensesDeviceDTO;
import com.iwomy.secureplat.platform.entity.BasicExpensesDeptDetailEntity;
import com.iwomy.secureplat.platform.entity.BasicConsumptionRecordEntity;
import com.iwomy.secureplat.platform.exception.PlatformException;
import com.iwomy.secureplat.platform.utils.RemoteDeptUtils;
import com.iwomy.secureplat.platform.mapper.BasicExpensesDeptDetailMapper;
import com.iwomy.secureplat.platform.service.BasicExpensesDeptDetailService;
import com.iwomy.secureplat.platform.service.BasicConsumptionRecordService;
import com.iwomy.secureplat.platform.vo.BasicExpensesDeptDetailVO;
import com.iwomy.secureplat.platform.vo.QuerySmsTtsCountVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 单位资费配置详情
 *
 * @author pig
 * @date 2023-12-04 13:54:08
 */
@Slf4j
@Service
public class BasicExpensesDeptDetailServiceImpl extends ServiceImpl<BasicExpensesDeptDetailMapper, BasicExpensesDeptDetailEntity> implements BasicExpensesDeptDetailService {

	private int smsRemainNum = 0;//短信剩余数量
	private int payingSmsRemainNum = 0;//代付最新短信总限制剩余数量
	private int payingSmsDayRemainNum = 0;//代付最新短信日限剩余数量
	private int payingSmsMonthRemainNum = 0;//代付最新短信月限剩余数量
	private int ttsRemainNum = 0;//语音剩余数量
	private int payingTtsRemainNum = 0;//代付最新语音总限制剩余数量
	private int payingTtsDayRemainNum = 0;//代付最新短信日限剩余数量
	private int payingTtsMonthRemainNum = 0;//代付最新短信月限剩余数量
	private int deviceRemainNum = 0;//设备剩余数量
	private int platformFeeYears = 0;//平台总年限
	private LocalDateTime recentTime;
	private int deliveryMethod;
	private LocalDateTime smsExpirationDate;
	private LocalDateTime ttsExpirationDate;

	@Autowired
	private RemoteDeptUtils remoteDeptUtils;

	@Autowired
	private BasicConsumptionRecordService basicConsumptionRecordService;

	@Override
	public List<SysDeptVO> getBasicExpensesDeptDetailPage(Page page, BasicExpensesDeviceDTO expensesDeviceDTO) {
		List<SysDeptVO> deptList = (List<SysDeptVO>) remoteDeptUtils.getAllDeptList(expensesDeviceDTO.getDeptName()).getData();
		if (deptList == null) return new ArrayList<>();
		Map<Long, List<BasicExpensesDeptDetailEntity>> deptDetailsMap = deptList.stream()
				.collect(Collectors.toMap(
						SysDeptVO::getDeptId,
						dept -> byDeptIdList(dept.getDeptId())
				));
		deptList.forEach(dept -> {
			Long deptId = dept.getDeptId();
			List<BasicExpensesDeptDetailEntity> deptDetails = deptDetailsMap.get(deptId);
			selectTotal(deptDetails);

			deptDetails.forEach(record -> {
				if (deliveryMethod == 20) {
					dept.setDeliveryMethod(deliveryMethod);
					dept.setSmsExpirationDate(smsExpirationDate);
					dept.setTtsExpirationDate(ttsExpirationDate);
				} else {
					dept.setDeliveryMethod(record.getDeliveryMethod());
					dept.setSmsTotalLimit(record.getSmsTotalLimit());
					dept.setTtsTotalLimit(record.getTtsTotalLimit());
					dept.setSmsExpirationDate(record.getSmsExpirationDate());
					dept.setTtsExpirationDate(record.getTtsExpirationDate());
				}
			});

			Optional.ofNullable(dept.getDeliveryMethod()).ifPresent(deliveryMethod -> {
				if (payingSmsRemainNum != 999999) {
					dept.setSmsRemainNum(smsRemainNum + payingSmsRemainNum);
				} else {
					dept.setSmsRemainNum(payingSmsRemainNum);
				}
				if (payingTtsRemainNum != 999999) {
					dept.setTtsRemainNum(ttsRemainNum + payingTtsRemainNum);
				} else {
					dept.setTtsRemainNum(payingTtsRemainNum);
				}
				dept.setDeviceRemainNum(deviceRemainNum);

			});

			Optional<BasicExpensesDeptDetailEntity> recordWithMaxDate = deptDetails.stream()
					.max(Comparator.comparing(BasicExpensesDeptDetailEntity::getPlatformExpireDate));
			recordWithMaxDate.ifPresent(record -> {
				dept.setPlatformExpireDate(record.getPlatformExpireDate());
			});

			dept.setPlatformFeeYears(platformFeeYears);

		});


		List<SysDeptVO> tree = new ArrayList<>();
		if (StrUtil.isNotEmpty(expensesDeviceDTO.getDeptName())) {
			tree = deptList;
		} else {
			Long parentId = null;
			for (SysDeptVO dept : deptList) {
				if (SecurityUtils.getUser().getDeptId().equals(dept.getDeptId())) {
					parentId = dept.getParentId();
					break;
				}
			}
			tree = buildTree(deptList, parentId);

		}

		return tree;
	}

	//根据单位id查询赠送记录
	@Override
	public List<BasicExpensesDeptDetailVO> byDeptId(Long deptId) {
		LambdaQueryWrapper<BasicExpensesDeptDetailEntity> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(BasicExpensesDeptDetailEntity::getDeptId, deptId);

		List<BasicExpensesDeptDetailEntity> deptDetails = this.getBaseMapper().selectList(wrapper);

		List<BasicExpensesDeptDetailVO> deptDetailVOs = deptDetails.stream().map(deptDetail -> {
			BasicExpensesDeptDetailVO deptDetailVO = new BasicExpensesDeptDetailVO();
			BeanUtils.copyProperties(deptDetail, deptDetailVO);
			return deptDetailVO;
		}).collect(Collectors.toList());

		Map<String, Object> data = remoteDeptUtils.getDept(deptId);
		String deptName = (String) data.getOrDefault("name", null);
		deptDetailVOs.forEach(basicExpensesDeptDetailVO -> basicExpensesDeptDetailVO.setDeptName(deptName));
		return deptDetailVOs;
	}

	//配送新增
	@Override
	public R newlyAdded(BasicExpensesDeptDetailEntity basicExpensesDeptDetail) {
		Long customerDeptId = basicExpensesDeptDetail.getDeptId();
		BasicExpensesDeptDetailEntity newBasicExpensesDeptDetail = new BasicExpensesDeptDetailEntity();
		BeanUtils.copyProperties(basicExpensesDeptDetail, newBasicExpensesDeptDetail);
		newBasicExpensesDeptDetail.setDeptId(SecurityUtils.getUser().getDeptId());

		deliveryadded(newBasicExpensesDeptDetail, -1, SecurityUtils.getUser().getDeptId(), customerDeptId);

		deviceRemainNum = 0;
		Long DeptId = basicExpensesDeptDetail.getDeptId();
		if (DeptId != null) {
			deliveryadded(basicExpensesDeptDetail, 1, DeptId, customerDeptId);
		}
		return R.ok();
	}

	//配送新增
	private R deliveryadded(BasicExpensesDeptDetailEntity expensesDeptDetail, int sign, Long deptId, Long customerDeptId) {
		List<BasicExpensesDeptDetailEntity> basicExpensesDeptDetails = byDeptIdList(deptId);
		LocalDateTime expireDate = null;
		for (BasicExpensesDeptDetailEntity record : basicExpensesDeptDetails) {
			expireDate = record.getPlatformExpireDate();
		}
		//计算短信语音剩余
		selectTotal(basicExpensesDeptDetails);

		Map<String, Object> data = remoteDeptUtils.getDept(SecurityUtils.getUser().getDeptId());
		String parentIdString = (String) data.getOrDefault("parentId", null);
		Long parentId = Long.parseLong(parentIdString);

		if (parentId != 0) {
			//本级不是租户时，给下级配送时，只判断本级的
			if (deptId == SecurityUtils.getUser().getDeptId()) {
				if (smsRemainNum < expensesDeptDetail.getSmsAddNum() ||
						ttsRemainNum < expensesDeptDetail.getTtsAddNum() ||
						deviceRemainNum < expensesDeptDetail.getDeviceAddNum()) {
					throw new PlatformException("短信/语音/设备剩余量不足！");
				}
			}
		}

		if (sign == -1) {
			//配送单位（本单位）修改数量以及记录
			highDept(expensesDeptDetail, deptId, parentId, customerDeptId);
			deviceRemainNum = 0;
		} else {
			//下级单位新增数量进单位资费记录中
			expensesDeptDetail.setSmsRemainNum(smsRemainNum + expensesDeptDetail.getSmsAddNum());
			expensesDeptDetail.setSmsAddNumRemain(expensesDeptDetail.getSmsAddNum());
			expensesDeptDetail.setTtsRemainNum(ttsRemainNum + expensesDeptDetail.getTtsAddNum());
			expensesDeptDetail.setTtsAddNumRemain(expensesDeptDetail.getTtsAddNum());
			expensesDeptDetail.setDeviceAddNumRemain(expensesDeptDetail.getDeviceAddNum());
			expensesDeptDetail.setDeviceRemainNum(deviceRemainNum + expensesDeptDetail.getDeviceAddNum());
			expensesDeptDetail.setSmsAddNum(expensesDeptDetail.getSmsAddNum());
			expensesDeptDetail.setTtsAddNum(expensesDeptDetail.getTtsAddNum());
			expensesDeptDetail.setDeviceAddNum(expensesDeptDetail.getDeviceAddNum());
			expensesDeptDetail.setDeptId(deptId);

			LocalDateTime newPlatformExpireDate = null;
			if (expireDate != null) {
				//到期时间，如果原本有到期时间，则到期时间+年限
				newPlatformExpireDate = expireDate.plusYears(expensesDeptDetail.getAddPlatformFeeYears());
			} else {
				//到期时间，如果原本没有年限，则设置为当前时间+年限
				newPlatformExpireDate = LocalDateTime.now().plusYears(expensesDeptDetail.getAddPlatformFeeYears());
			}
			expensesDeptDetail.setPlatformExpireDate(newPlatformExpireDate);
			//总年限=当前总年限+新增年限
			expensesDeptDetail.setPlatformFeeYears(platformFeeYears + expensesDeptDetail.getAddPlatformFeeYears());
			this.save(expensesDeptDetail);
		}
		return R.ok();
	}

	//新增配送单位的数据修改,写进短信语音消费记录中
	private void highDept(BasicExpensesDeptDetailEntity expensesDeptDetail, Long deptId, Long parentId, Long customerDeptId) {
		//不是租户时
		if (parentId != 0) {
			//扣除本单位的设备数
			int deviceAddNum = expensesDeptDetail.getDeviceAddNum();
			deductDevice(deviceAddNum, deptId);
			//扣除本单位的短信数
			int smsAddNum = expensesDeptDetail.getSmsAddNum();
			deptDeductSms(smsAddNum, deptId);
			//扣除本单位的语音数
			int ttsAddNum = expensesDeptDetail.getTtsAddNum();
			deptDeductTts(ttsAddNum, deptId);
		}
		//本单位分配给下级单位成功后写进短信语音消费记录中
		if (expensesDeptDetail.getSmsAddNum() != null) {
			BasicConsumptionRecordEntity basicConsumptionRecord = new BasicConsumptionRecordEntity();
			basicConsumptionRecord.setDeptId(deptId);
			basicConsumptionRecord.setUsedType(10);
			basicConsumptionRecord.setNotificationType(10);
			basicConsumptionRecord.setSmsNumber(expensesDeptDetail.getSmsAddNum());
			basicConsumptionRecord.setCustomerDeptId(customerDeptId);
			basicConsumptionRecordService.save(basicConsumptionRecord);
		}
		if (expensesDeptDetail.getTtsAddNum() != null) {
			BasicConsumptionRecordEntity basicConsumptionRecord = new BasicConsumptionRecordEntity();
			basicConsumptionRecord.setDeptId(deptId);
			basicConsumptionRecord.setUsedType(10);
			basicConsumptionRecord.setNotificationType(20);
			basicConsumptionRecord.setTtsNumber(expensesDeptDetail.getTtsAddNum());
			basicConsumptionRecord.setCustomerDeptId(customerDeptId);
			basicConsumptionRecordService.save(basicConsumptionRecord);
		}

	}

	//给下级单位配置代付写进消费记录中
	private void saveConsumptionRecord20(BasicExpensesDeptDetailEntity expensesDeptDetail, Long deptId, Long customerDeptId) {
		//本单位分配给下级单位成功后写进短信语音消费记录中
		if (expensesDeptDetail.getSmsTotalLimit() != null) {
			BasicConsumptionRecordEntity basicConsumptionRecord = new BasicConsumptionRecordEntity();
			basicConsumptionRecord.setDeptId(deptId);
			basicConsumptionRecord.setUsedType(20);
			basicConsumptionRecord.setNotificationType(10);
			basicConsumptionRecord.setSmsNumber(expensesDeptDetail.getSmsTotalLimit());
			basicConsumptionRecord.setCustomerDeptId(customerDeptId);
			basicConsumptionRecordService.save(basicConsumptionRecord);
		}
		if (expensesDeptDetail.getTtsTotalLimit() != null) {
			BasicConsumptionRecordEntity basicConsumptionRecord = new BasicConsumptionRecordEntity();
			basicConsumptionRecord.setDeptId(deptId);
			basicConsumptionRecord.setUsedType(20);
			basicConsumptionRecord.setNotificationType(20);
			basicConsumptionRecord.setTtsNumber(expensesDeptDetail.getTtsTotalLimit());
			basicConsumptionRecord.setCustomerDeptId(customerDeptId);
			basicConsumptionRecordService.save(basicConsumptionRecord);
		}
	}

	//代付配置
	@Override
	public R paying(BasicExpensesDeptDetailEntity basicExpensesDeptDetail) {
		if (basicExpensesDeptDetail.getDeptLimit() == 10) {
			// 本级及子级
			List<SysDept> deptList = (List<SysDept>) remoteDeptUtils.getDescendantList(basicExpensesDeptDetail.getDeptId()).getData();
			List<Long> deptIds = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());

			for (Long deptId : deptIds) {
				BasicExpensesDeptDetailEntity expensesDeptDetail = new BasicExpensesDeptDetailEntity();
				BeanUtils.copyProperties(basicExpensesDeptDetail, expensesDeptDetail);
				expensesDeptDetail.setDeptId(deptId);

				addPaying(expensesDeptDetail, 1, deptId);
			}
		} else if (basicExpensesDeptDetail.getDeptLimit() == 20) {
			Long DeptId = basicExpensesDeptDetail.getDeptId();
			if (DeptId != null) {
				addPaying(basicExpensesDeptDetail, 1, DeptId);
			}
		}
		return R.ok();
	}

	//代付配置
	private R addPaying(BasicExpensesDeptDetailEntity basicExpensesDeptDetail, int sign, Long deptId) {
		List<BasicExpensesDeptDetailEntity> basicExpensesDeptDetails = byDeptIdList(deptId);
		selectTotal(basicExpensesDeptDetails);
		if (basicExpensesDeptDetail.getPaymentType() == 10) {
			sms(basicExpensesDeptDetail, sign, smsRemainNum);
			tts(basicExpensesDeptDetail, sign, ttsRemainNum);
		} else if (basicExpensesDeptDetail.getPaymentType() == 20) {
			sms(basicExpensesDeptDetail, sign, smsRemainNum);
			basicExpensesDeptDetail.setTtsRemainNum(ttsRemainNum);
		} else if (basicExpensesDeptDetail.getPaymentType() == 30) {
			tts(basicExpensesDeptDetail, sign, ttsRemainNum);
			basicExpensesDeptDetail.setSmsRemainNum(smsRemainNum);
		}
		basicExpensesDeptDetail.setDeptLimit(basicExpensesDeptDetail.getDeptLimit());
		basicExpensesDeptDetail.setDeviceRemainNum(deviceRemainNum);
		basicExpensesDeptDetail.setDeptId(deptId);
		basicExpensesDeptDetail.setPlatformFeeYears(platformFeeYears);
		if (recentTime != null) {
			basicExpensesDeptDetail.setPlatformExpireDate(recentTime);
		}
		this.save(basicExpensesDeptDetail);
		saveConsumptionRecord20(basicExpensesDeptDetail, SecurityUtils.getUser().getDeptId(), deptId);
		return R.ok();
	}

	//短信代付
	private void sms(BasicExpensesDeptDetailEntity basicExpensesDeptDetail, int sign, int smsRemainNum) {
		if (basicExpensesDeptDetail.getSmsTotalLimit() == 999999) {
			basicExpensesDeptDetail.setSmsAddNum(basicExpensesDeptDetail.getSmsTotalLimit());
			basicExpensesDeptDetail.setSmsRemainNum(basicExpensesDeptDetail.getSmsTotalLimit());
		} else {
			basicExpensesDeptDetail.setSmsRemainNum(smsRemainNum + basicExpensesDeptDetail.getSmsTotalLimit());
			basicExpensesDeptDetail.setSmsAddNum(sign * basicExpensesDeptDetail.getSmsTotalLimit());
		}
		basicExpensesDeptDetail.setSmsAddNumRemain(basicExpensesDeptDetail.getSmsTotalLimit());
		basicExpensesDeptDetail.setSmsSumDayRemain(basicExpensesDeptDetail.getSmsSumDay());
		basicExpensesDeptDetail.setSmsSumMonthRemain(basicExpensesDeptDetail.getSmsSumMonth());
		basicExpensesDeptDetail.setSmsExpirationDate(basicExpensesDeptDetail.getSmsExpirationDate());
	}

	//语音代付
	private void tts(BasicExpensesDeptDetailEntity basicExpensesDeptDetail, int sign, int ttsRemainNum) {
		if (basicExpensesDeptDetail.getTtsTotalLimit() == 999999) {
			basicExpensesDeptDetail.setTtsAddNum(basicExpensesDeptDetail.getTtsTotalLimit());
			basicExpensesDeptDetail.setTtsRemainNum(basicExpensesDeptDetail.getTtsTotalLimit());
		} else {
			basicExpensesDeptDetail.setTtsRemainNum(ttsRemainNum + basicExpensesDeptDetail.getTtsTotalLimit());
			basicExpensesDeptDetail.setTtsAddNum(sign * basicExpensesDeptDetail.getTtsTotalLimit());
		}
		basicExpensesDeptDetail.setTtsAddNumRemain(basicExpensesDeptDetail.getTtsTotalLimit());
		basicExpensesDeptDetail.setTtsSumDayRemain(basicExpensesDeptDetail.getTtsSumDay());
		basicExpensesDeptDetail.setTtsSumMonthRemain(basicExpensesDeptDetail.getTtsSumMonth());
		basicExpensesDeptDetail.setTtsExpirationDate(basicExpensesDeptDetail.getTtsExpirationDate());
	}

	//代付详情
	@Override
	public BasicExpensesDeptDetailEntity payingDetails(Long deptId) {
		BasicExpensesDeptDetailEntity latestRecord = this.lambdaQuery()
				.eq(BasicExpensesDeptDetailEntity::getDeptId, deptId)
				.eq(BasicExpensesDeptDetailEntity::getDeliveryMethod, 20)
				.orderByDesc(BasicExpensesDeptDetailEntity::getCreateTime)
				.last("LIMIT 1")
				.one();
		return latestRecord;
	}

	//查询单位可用年限集合
	@Override
	public List<Integer> getPlatformFeeYears(Long customerDeptId) {
		Map<String, Object> data = remoteDeptUtils.getDept(customerDeptId);
		String parentIdString = (String) data.getOrDefault("parentId", null);
		Long parentId = Long.parseLong(parentIdString);
		List<Integer> yearList = new ArrayList<>();
		if (parentId.equals(0L)) {
			for (int i = 1; i <= 999; i++) {
				yearList.add(i);
			}
		} else {
			LambdaQueryWrapper<BasicExpensesDeptDetailEntity> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(BasicExpensesDeptDetailEntity::getDeptId, customerDeptId);
			wrapper.orderByDesc(BasicExpensesDeptDetailEntity::getPlatformExpireDate);
			wrapper.last("LIMIT 1");
			BasicExpensesDeptDetailEntity basicExpensesDeptDetail = this.getBaseMapper().selectOne(wrapper);

			if (basicExpensesDeptDetail != null) {
				LocalDateTime currentDate = LocalDateTime.now();
				LocalDateTime expireDate = basicExpensesDeptDetail.getPlatformExpireDate();
				long numberOfYears = ChronoUnit.YEARS.between(currentDate, expireDate);
//				if (ChronoUnit.DAYS.between(currentDate, expireDate) % 365 == 0) {
//					numberOfYears++; // 不足一年按照一年计算
//				}
				for (int i = 0; i <= numberOfYears; i++) {
					yearList.add(i);
				}
			}
		}
		return yearList;
	}

	//查询资费详情
	@Override
	public QuerySmsTtsCountVO querySmsTtsCount() {
		Long deptId = SecurityUtils.getUser().getDeptId();
		return getBasicExpensesDeptDetails(deptId);
	}

	@Override
	public QuerySmsTtsCountVO queryDeptCount(Long deptId) {
		return getBasicExpensesDeptDetails(deptId);
	}

	private QuerySmsTtsCountVO getBasicExpensesDeptDetails(Long deptId) {
		QuerySmsTtsCountVO querySmsTtsCountVO = new QuerySmsTtsCountVO();
		List<BasicExpensesDeptDetailEntity> basicExpensesDeptDetails = byDeptIdList(deptId);
		LocalDateTime expireDate = null;

		for (BasicExpensesDeptDetailEntity record : basicExpensesDeptDetails) {
			LocalDateTime recordExpireDate = record.getPlatformExpireDate();

			if (expireDate == null || recordExpireDate.isAfter(expireDate)) {
				expireDate = recordExpireDate;
			}
		}
		selectTotal(basicExpensesDeptDetails);
		querySmsTtsCountVO.setSmsRemainNum(smsRemainNum);
		querySmsTtsCountVO.setTtsRemainNum(ttsRemainNum);
		querySmsTtsCountVO.setDeviceRemainNum(deviceRemainNum);
		querySmsTtsCountVO.setPlatformFeeYears(platformFeeYears);
		querySmsTtsCountVO.setPlatformExpireDate(expireDate);

		querySmsTtsCountVO.setPayingSmsRemainNum(payingSmsRemainNum);
		querySmsTtsCountVO.setPayingSmsDayRemainNum(payingSmsDayRemainNum);
		querySmsTtsCountVO.setPayingSmsMonthRemainNum(payingSmsMonthRemainNum);
		querySmsTtsCountVO.setPayingTtsRemainNum(payingTtsRemainNum);
		querySmsTtsCountVO.setPayingTtsDayRemainNum(payingTtsDayRemainNum);
		querySmsTtsCountVO.setPayingTtsMonthRemainNum(payingTtsMonthRemainNum);
		return querySmsTtsCountVO;
	}

	//单位配置查询时返回树形列表
	private List<SysDeptVO> buildTree(List<SysDeptVO> deptList, Long parentId) {
		List<SysDeptVO> tree = new ArrayList<>();
		for (SysDeptVO dept : deptList) {
			if (parentId.equals(dept.getParentId())) {
				List<SysDeptVO> children = buildTree(deptList, dept.getDeptId());
				if (!children.isEmpty()) {
					dept.setChildren(children);
				} else {
					dept.setChildren(null);
				}
				tree.add(dept);
			}
		}
		return tree;
	}


	@Override
	public List<BasicExpensesDeptDetailEntity> byDeptIdList(Long deptId) {
		QueryWrapper<BasicExpensesDeptDetailEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("dept_id", deptId);
		List<BasicExpensesDeptDetailEntity> deptDetails = this.getBaseMapper().selectList(wrapper);
		return deptDetails;
	}

	//计算单位的短信语音设备数量
	private void selectTotal(List<BasicExpensesDeptDetailEntity> deptDetails) {
		smsRemainNum = 0;
		ttsRemainNum = 0;
		payingSmsRemainNum = 0;
		payingSmsDayRemainNum = 0;
		payingSmsMonthRemainNum = 0;
		payingTtsRemainNum = 0;
		payingTtsDayRemainNum = 0;//代付最新短信日限剩余数量
		payingTtsMonthRemainNum = 0;//代付最新短信月限剩余数量
		deliveryMethod = 0;
		smsExpirationDate = null;
		ttsExpirationDate = null;
		platformFeeYears=0;
		deviceRemainNum =0;
		Optional<BasicExpensesDeptDetailEntity> recordWithMaxDate = deptDetails.stream()
				.max(Comparator.comparing(BasicExpensesDeptDetailEntity::getPlatformExpireDate));
		recordWithMaxDate.ifPresent(record -> {
			recentTime = record.getPlatformExpireDate();
		});

		//单位资费记录表，上级分配的数-本级分配下级使用的数（通知记录里）
		smsRemainNum = deptDetails.stream()
				.filter(record -> record.getSmsAddNumRemain() != null && record.getSmsAddNumRemain() != 999999)
				.filter(record -> record.getDeliveryMethod() == 10)
				.mapToInt(BasicExpensesDeptDetailEntity::getSmsAddNumRemain)
				.sum();
		log.info("单位短信剩余量:{}" + smsRemainNum);

		ttsRemainNum = deptDetails.stream()
				.filter(record -> record.getTtsAddNumRemain() != null && record.getTtsAddNumRemain() != 999999)
				.filter(record -> record.getDeliveryMethod() == 10)
				.mapToInt(BasicExpensesDeptDetailEntity::getTtsAddNumRemain)
				.sum();
		log.info("单位语音剩余量:{}" + ttsRemainNum);

		//代付的最新一条记录
		payingLastRecord(deptDetails);

		platformFeeYears = deptDetails.stream()
				.filter(record -> record.getAddPlatformFeeYears() != null)
				.mapToInt(BasicExpensesDeptDetailEntity::getAddPlatformFeeYears)
				.sum();

		deviceRemainNum = deptDetails.stream()
				.filter(record -> record.getDeviceAddNumRemain() != null)
				.mapToInt(BasicExpensesDeptDetailEntity::getDeviceAddNumRemain)
				.sum();
	}

	private Optional<BasicExpensesDeptDetailEntity> payingLastRecord(List<BasicExpensesDeptDetailEntity> deptDetails) {
		LocalDateTime currentDateTime = LocalDateTime.now(); // 获取当前日期和时间
		//获取代付最新一条数据
		Optional<BasicExpensesDeptDetailEntity> latestRecord = deptDetails.stream()
				.filter(record -> record.getDeliveryMethod() == 20)
				.sorted(Comparator.comparing(BasicExpensesDeptDetailEntity::getCreateTime).reversed()) // 按照 CreateTime 降序排序
				.findFirst(); // 获取第一条记录

		if (latestRecord.isPresent()) {
			BasicExpensesDeptDetailEntity record = latestRecord.get();
			// 判断短信代付时间是否到期
			if (record.getSmsExpirationDate() != null && currentDateTime.isBefore(record.getSmsExpirationDate())) {
				payingSmsRemainNum = record.getSmsAddNumRemain();
				payingSmsDayRemainNum = record.getSmsSumDayRemain();
				payingSmsMonthRemainNum = record.getSmsSumMonthRemain();
				deliveryMethod = 20;
				smsExpirationDate = record.getSmsExpirationDate();
			}
			// 判断语音代付时间是否到期
			if (record.getTtsExpirationDate() != null && currentDateTime.isBefore(record.getTtsExpirationDate())) {
				payingTtsRemainNum = record.getTtsAddNumRemain();
				payingTtsDayRemainNum = record.getTtsSumDayRemain();
				payingTtsMonthRemainNum = record.getTtsSumMonthRemain();
				deliveryMethod = 20;
				ttsExpirationDate = record.getTtsExpirationDate();
			}
		}
		return latestRecord;
	}

	//单位设备数扣除
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deductDevice(int deviceAddNum, Long deptId) {
		// 先查询本单位的记录
		LambdaQueryWrapper<BasicExpensesDeptDetailEntity> wrapper = new LambdaQueryWrapper<>();
		wrapper.in(BasicExpensesDeptDetailEntity::getDeptId, deptId);

		List<BasicExpensesDeptDetailEntity> expensesDeptDetail = this.getBaseMapper().selectList(wrapper);
		List<BasicExpensesDeptDetailEntity> unexpiredRecords = expensesDeptDetail.stream()
				.sorted(Comparator.comparing(BasicExpensesDeptDetailEntity::getCreateTime))
				.filter(record -> record.getDeviceAddNumRemain() > 0)
				.collect(Collectors.toList());
		// 按时间顺序扣除设备
		boolean success = false;
		for (BasicExpensesDeptDetailEntity record : unexpiredRecords) {
			int remain = record.getDeviceAddNumRemain();
			int toDeduct = Math.min(remain, deviceAddNum);// 本次扣除的设备数量取决于剩余的设备数量
			record.setDeviceAddNumRemain(remain - toDeduct);
			success = this.updateById(record);
			if (!success) {
				break;
			}
			deviceAddNum -= toDeduct;// 更新剩余的设备数量
			if (deviceAddNum <= 0) {// 如果没有剩余的设备需要扣除，则跳出循环
				success = true;
				break;
			}
		}
		return success;
	}

	//单位短信数扣除
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deptDeductSms(int smsAddNum, Long deptId) {
		// 先查询本单位的记录
		LambdaQueryWrapper<BasicExpensesDeptDetailEntity> wrapper = new LambdaQueryWrapper<>();
		wrapper.in(BasicExpensesDeptDetailEntity::getDeptId, deptId);

		List<BasicExpensesDeptDetailEntity> expensesDeptDetail = this.getBaseMapper().selectList(wrapper);
		//配送的列表
		List<BasicExpensesDeptDetailEntity> deliveryMethod10 = expensesDeptDetail.stream()
				.sorted(Comparator.comparing(BasicExpensesDeptDetailEntity::getCreateTime))
				.filter(record -> record.getDeliveryMethod() == 10 && record.getSmsAddNumRemain() > 0)
				.collect(Collectors.toList());

		boolean success = false;
		// 按时间顺序扣除设备
		for (BasicExpensesDeptDetailEntity record : deliveryMethod10) {
			int toDeduct = Math.min(record.getSmsAddNumRemain(), smsAddNum);
			record.setSmsAddNumRemain(record.getSmsAddNumRemain() - toDeduct);
			success = this.updateById(record);
			if (!success) {
				break;
			}
			smsAddNum -= toDeduct;
			if (smsAddNum <= 0) {// 如果没有剩余的设备需要扣除，则跳出循环
				success = true;
				break;
			}
		}
		return success;
	}

	//单位语音数扣除
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deptDeductTts(int ttsAddNum, Long deptId) {
		// 先查询本单位的记录
		LambdaQueryWrapper<BasicExpensesDeptDetailEntity> wrapper = new LambdaQueryWrapper<>();
		wrapper.in(BasicExpensesDeptDetailEntity::getDeptId, deptId);

		List<BasicExpensesDeptDetailEntity> expensesDeptDetail = this.getBaseMapper().selectList(wrapper);
		//配送的列表
		List<BasicExpensesDeptDetailEntity> deliveryMethod10 = expensesDeptDetail.stream()
				.sorted(Comparator.comparing(BasicExpensesDeptDetailEntity::getCreateTime))
				.filter(record -> record.getDeliveryMethod() == 10 && record.getTtsAddNumRemain() > 0)
				.collect(Collectors.toList());

		boolean success = false;
		// 按时间顺序扣除设备
		for (BasicExpensesDeptDetailEntity record : deliveryMethod10) {
			int toDeduct = Math.min(record.getTtsAddNumRemain(), ttsAddNum);
			record.setTtsAddNumRemain(record.getTtsAddNumRemain() - toDeduct);
			success = this.updateById(record);
			if (!success) {
				break;
			}
			ttsAddNum -= toDeduct;
			if (ttsAddNum <= 0) {// 如果没有剩余的设备需要扣除，则跳出循环
				success = true;
				break;
			}
		}
		return success;
	}

	@Override
	public Integer deviceRemainNum() {
		List<SysDept> deptList = (List<SysDept>) remoteDeptUtils.getAllDept().getData();
		List<Long> childDeptIds = new ArrayList<>();
		for (SysDept dept : deptList) {
			if (SecurityUtils.getUser().getDeptId().equals(dept.getParentId())) {
				childDeptIds.add(dept.getDeptId());
			}
		}
		QueryWrapper<BasicExpensesDeptDetailEntity> wrapper = new QueryWrapper<>();
		if (!childDeptIds.isEmpty()) {
			wrapper.in("dept_id", childDeptIds);
		} else {
			childDeptIds.add(0L);
			wrapper.in("dept_id", childDeptIds);
		}

		wrapper.between("create_time",
				LocalDateTime.of(LocalDate.now().withDayOfMonth(1), LocalTime.MIN),
				LocalDateTime.of(LocalDate.now().withDayOfMonth(LocalDate.now().lengthOfMonth()), LocalTime.MAX)
		);
		List<BasicExpensesDeptDetailEntity> deviceCount = this.getBaseMapper().selectList(wrapper);
		deviceRemainNum = deviceCount.stream()
				.filter(record -> record.getDeviceAddNum() != null)
				.mapToInt(BasicExpensesDeptDetailEntity::getDeviceAddNum)
				.sum();
		return deviceRemainNum;
	}
}